package com.example.administrator.im.ui.activity;

import android.Manifest;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.im.R;
import com.example.administrator.im.utils.DisplayUtils;
import com.example.administrator.im.utils.EMUtils;
import com.example.administrator.im.adapter.ChatRoomAdapter;
import com.example.administrator.im.config.PhoneParam;
import com.example.administrator.im.data.IMData;
import com.example.administrator.im.ui.fragment.IMFragment;
import com.example.administrator.im.utils.NotificationUtils;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMMessage;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;

/**
 * create:2018/10/2 16:14
 * author: 姚鸿杰
 **/
public class ChatRoomActivity extends AppCompatActivity implements View.OnClickListener {

    private final String TAG = "ChatRoomActivity";

    private int rootHeight;
    private int inputHeight = 0;
    private int rv_height;

    private ViewGroup rootView;
    private EditText et_input;
    private ImageView iv_util;
    private Button btn_msg;

    private ViewGroup vg_utils;
    private ViewGroup vg_input;
    private LinearLayoutManager manager;

    private RecyclerView rv_msg;
    private ChatRoomAdapter adapter;

    private TextView tv_chat_name;
    private ImageView iv_back;
    private ViewGroup open_album;

    private boolean isPopup = false;    //是否弹出输入法

    private String username = "";
    private String nickname = "";

    private final int COUNT = 15;   //初始化跟每次刷新最多获取15条记录

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_room);

        Intent intent = getIntent();

        if (intent != null) {
            username = intent.getStringExtra("username");
            nickname = intent.getStringExtra("nickname");
        }
        rootHeight = PhoneParam.getInstance(ChatRoomActivity.this).getActivity_height();
        initView();
        EventBus.getDefault().register(this);
        EMUtils.setMsgAcked(username);  //设置消息为已读

        //获取聊天记录
        List<EMMessage> list = EMUtils.getChattingRecords(username, COUNT, true);
        for (EMMessage msg : list) {
            adapter.addMsg(new IMData(msg, true));
        }
        manager.scrollToPositionWithOffset(adapter.getItemCount() - 1, 0);  //定位到最后一条消息
        //清除所有通知
        NotificationUtils.cancelAllNotify();

        Log.d(TAG, "onCreate");
    }

    private boolean isFirst = false;
    private int screenHeight;
    private int inputShowHeight;

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(username)) {
            EventBus.getDefault().post(new IMFragment.IsAcked(username));
        }
        getWindow().getDecorView().addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {

                if (!isFirst) {
                    isFirst = true;
                    return;
                }

                //获取View可见区域的bottom
                Rect rect = new Rect();
                getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);

                if (bottom != 0 && oldBottom != 0 && bottom - rect.bottom <= 0) {
//                    Toast.makeText(ChatRoomActivity.this, "隐藏", Toast.LENGTH_SHORT).show();
                    isPopup = false;    //已关闭输入法
                    screenHeight = rootView.getMeasuredHeight();

                    //隐藏输入法时，如果工具栏也隐藏
                    if (vg_utils.getVisibility() == View.GONE) {
                        exitUtils();
                    }
                    return;
                } else {
//                    Toast.makeText(ChatRoomActivity.this, "弹出", Toast.LENGTH_SHORT).show();
                    inputShowHeight = screenHeight - rootView.getMeasuredHeight();
                    showInputMethod();
                    return;
                }
            }
        });
    }

    private void initView() {

        iv_util = (ImageView) findViewById(R.id.util);
        btn_msg = (Button) findViewById(R.id.send_msg);
        vg_utils = (ViewGroup) findViewById(R.id.utils);
        rootView = (ViewGroup) findViewById(R.id.rootView);
        vg_input = (ViewGroup) findViewById(R.id.relativeLayout2);
        rv_msg = (RecyclerView) findViewById(R.id.rv_msg);
        tv_chat_name = (TextView) findViewById(R.id.chat_name);
        iv_back = (ImageView) findViewById(R.id.iv_back);
        tv_chat_name.setText(nickname);

        initRecycler();

        rv_msg.post(new Runnable() {
            @Override
            public void run() {
                rv_height = rv_msg.getMeasuredHeight();
            }
        });

        iv_util.setOnClickListener(this);
        btn_msg.setOnClickListener(this);
        iv_back.setOnClickListener(this);

        et_input = (EditText) findViewById(R.id.et_input);
        //监听edittext
        et_input.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {//监听前的变化
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {//输入的内容变化的监听
            }

            @Override
            public void afterTextChanged(Editable s) {
                //监听后的变化
                afterChanged();
            }
        });

        open_album = (ViewGroup) findViewById(R.id.open_album);
        open_album.setOnClickListener(this);

    }

    private void initRecycler() {

        manager = new LinearLayoutManager(this);
        adapter = new ChatRoomAdapter(null, this);
        rv_msg.setLayoutManager(manager);
        rv_msg.setAdapter(adapter);
        manager.scrollToPositionWithOffset(adapter.getItemCount() - 1, 0);  //定位到最后一条消息
    }

    //监听输入法出现后的变化
    private void afterChanged() {

        if (et_input.getText().length() > 0) {
            btn_msg.setVisibility(View.VISIBLE);
            iv_util.setVisibility(View.INVISIBLE);
        } else {
            btn_msg.setVisibility(View.INVISIBLE);
            iv_util.setVisibility(View.VISIBLE);
        }
    }

    //判断是打开还是关闭工具栏
    private void openOrCloseUtil() {

        //第一次显示
        if (inputHeight == 0 && vg_utils.getVisibility() == View.GONE) {
            vg_utils.setVisibility(View.VISIBLE);
            iv_util.setImageResource(R.mipmap.util_c);
            rv_msg.scrollToPosition(adapter.getItemCount() - 1);
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) rv_msg.getLayoutParams();

            SharedPreferences spf = getSharedPreferences("inputMothod", Context.MODE_PRIVATE);
            int height = rv_height - spf.getInt("height", DisplayUtils.dip2px(this, 280));

            lp.height = height;
            lp.weight = 0f;
            rv_msg.setLayoutParams(lp);
            return;
        }

        //不是第一次打开
        if (vg_utils.getVisibility() == View.GONE) {
            vg_utils.setVisibility(View.VISIBLE);
            iv_util.setImageResource(R.mipmap.util_c);
            rv_msg.scrollToPosition(adapter.getItemCount() - 1);
            if (isPopup) {    //输入法显示时隐藏
                hideInputMethod();
            }
            showUtils(true);
            return;
        }

        if (vg_utils.getVisibility() == View.VISIBLE) {
            vg_utils.setVisibility(View.GONE);
            iv_util.setImageResource(R.mipmap.util);
            exitUtils();
        }
    }

    //显示工具栏操作
    private void showUtils(boolean isAlterUtilsHeight) {
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) rv_msg.getLayoutParams();
        lp.height = rv_height - inputHeight;
        lp.weight = 0f;
        rv_msg.setLayoutParams(lp);

        if (isAlterUtilsHeight) {
            ViewGroup.LayoutParams vglp = vg_utils.getLayoutParams();
            vglp.height = inputHeight;
            vg_utils.setLayoutParams(vglp);
        }
    }

    //退出工具栏
    private void exitUtils() {
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) rv_msg.getLayoutParams();
        lp.weight = 1f;
        rv_msg.setLayoutParams(lp);
    }

    //隐藏输入法
    private void hideInputMethod() {
        InputMethodManager inputMethodManager = (InputMethodManager) this.getApplicationContext().
                getSystemService(Context.INPUT_METHOD_SERVICE);

        inputMethodManager.hideSoftInputFromWindow(et_input.getWindowToken(), 0); //隐藏
    }

    //弹出输入法
    private void showInputMethod() {
        if (!isPopup) {
            rv_msg.scrollToPosition(adapter.getItemCount() - 1);
            if (inputHeight != rootHeight - rootView.getMeasuredHeight()) {
                inputHeight = rootHeight - rootView.getMeasuredHeight();

//                Log.e(TAG, inputShowHeight + "ii");
//                Log.e(TAG, inputHeight + "ii");

                SharedPreferences.Editor editor = getSharedPreferences("inputMothod", Context.MODE_PRIVATE).edit();
                editor.putInt("height", inputShowHeight);
                editor.apply();
            }

            //出现输入法时，如果工具栏已显示则隐藏工具栏
            if (vg_utils.getVisibility() == View.VISIBLE) {

                //如果工具栏的高度不等于输入法高度则让其相等
                if (vg_utils.getMeasuredHeight() != inputHeight)
                    showUtils(false);

                openOrCloseUtil();
            }
        }
        isPopup = true; //设置为true不再重复调用
    }

    //进入聊天设置
    public void openChatSetting(View v) {
        Intent intent = new Intent(this, ChatSettingActivity.class);
        intent.putExtra("username", username);
        startActivity(intent);
    }

    //发送消息
    private void sendMessage() {
        if (TextUtils.isEmpty(et_input.getText().toString())) {
            return;
        }
        final EMMessage message = EMUtils.sendMessage(et_input.getText().toString(), username);

        addMessage(message);

        //刷新消息列表
        EventBus.getDefault().post(new IMFragment.UpdateConversations(message, true));

        //定位到最后一条消息
        manager.scrollToPositionWithOffset(adapter.getItemCount() - 1, 0);  //定位到最后一条消息
        et_input.setText(""); //将消息置空
        //通过 message 设置消息的发送及接收状态
        message.setMessageStatusCallback(new EMCallBack() {

            //发送成功做处理
            @Override
            public void onSuccess() {
            }

            //发送失败做处理
            @Override
            public void onError(int i, String s) {
            }

            //发送中做处理
            @Override
            public void onProgress(int i, String s) {
            }
        });
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.send_msg:
                sendMessage();
                break;
            case R.id.util:
                openOrCloseUtil();
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.open_album:
                open_album();
                break;
        }
    }

    private final int ALBUM = 1;

    private void open_album() {
        //申请权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else {
            openAlbum();
        }
    }

    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, ALBUM);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == ALBUM) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openAlbum();
            } else {
                Toast.makeText(this, "权限不够请到设置里设置", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ALBUM) {
            if (resultCode == RESULT_OK) {
                handleImageOnKitKat(data);
            }
        }
    }


    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            imagePath = uri.getPath();
        }
        //把路径发送
        EMMessage msg = EMUtils.sendImageMessage(imagePath, username, false);
        addMessage(msg);

        //刷新消息列表
        EventBus.getDefault().post(new IMFragment.UpdateConversations(msg, true));

        //定位到最后一条消息
        manager.scrollToPositionWithOffset(adapter.getItemCount() - 1, 0);  //定位到最后一条消息
        et_input.setText(""); //将消息置空
        //通过 message 设置消息的发送及接收状态
        msg.setMessageStatusCallback(new EMCallBack() {

            //发送成功做处理
            @Override
            public void onSuccess() {
            }

            //发送失败做处理
            @Override
            public void onError(int i, String s) {
            }

            //发送中做处理
            @Override
            public void onProgress(int i, String s) {
            }
        });
        //sendMultipart(imagePath);
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    /**
     * 添加一条消息
     *
     * @param msg :接收或者发送的消息
     */
    private void addMessage(final EMMessage msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter.addMsg(new IMData(msg, true));
                rv_msg.scrollToPosition(adapter.getItemCount() - 1);
            }
        });
    }

    //重写返回按钮
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (vg_utils.getVisibility() == View.VISIBLE) {
                openOrCloseUtil();
                return false;
            } else
                this.finish();
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy");
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void addMsg(AddMsg msg) {
        //判断发送过来的消息是否与当前聊天对象一致
        String account = msg.getMsg().getUserName();
        if (account.equals(username)) {
            addMessage(msg.getMsg());
            EMUtils.setMsgAcked(msg.getMsg().getUserName());
        }
    }

    public static class AddMsg {
        private EMMessage msg;

        public AddMsg(EMMessage msg) {
            this.msg = msg;
        }

        public EMMessage getMsg() {
            return msg;
        }
    }

}